package com.czy.filter;

import com.czy.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*") //指定拦截的路径
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        //1. 获取请求url
        String requestURI = httpServletRequest.getRequestURI();

        //2. 判断请求url是否包含login，如果包含，说明是登录操作，放行
        if (requestURI.contains("/login")) {
            log.info("登录放行");
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        //3. 获取请求头中的令牌
        String token = httpServletRequest.getHeader("token");

        //4. 判断令牌是否存在，如果不存在，响应错误信息401
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，响应401");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //5. 解析token字符串令牌，如果解析失败，响应错误信息401
        try {
            Claims claims = JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌非法，响应401");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //6. 解析成功，校验通过，放行
        log.info("令牌合法，放行");
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
